package com.hc.security.config.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定义权限判断管理器
 * 一个请求先走FilterInvocationSecurityMetadataSource，然后再走AccessDecisionManager
 */
@Slf4j
@Component
public class SelfAccessDecisionManager implements AccessDecisionManager {

    /**
     * 判断当前登录的用户是否具备当前请求URL所需要的角色信息
     * 如不具备抛出AccessDeniedException异常
     * 否则不做任何事
     * @param authentication 当前登录用户信息
     * @param o FilterInvocation对象，可以获取当前请求对象
     * @param collection 请求当前URL所需要角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

        // 当前请求需要的权限
        log.info("collection:{}", collection);
        // 当前用户所具有的权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        log.info("principal:{} authorities:{}", authentication.getPrincipal().toString(), authorities);

        for (ConfigAttribute configAttribute : collection) {

            // 对所有人可访问做处理
            if("ROLE_ALL".equals(configAttribute.getAttribute())){
                return;
            }

            // 登录即可访问
            if("ROLE_LOGIN".equals(configAttribute.getAttribute()) && authentication instanceof UsernamePasswordAuthenticationToken){
                return;
            }

            // 当前请求需要的权限
            String needRole = configAttribute.getAttribute();
            if ("ROLE_WRONG".equals(needRole)) {
                //这个异常父类是AuthenticationException，表示没有权限
                throw new BadCredentialsException("Wrong path!!!!");
            }
            // 当前用户所具有的权限
            for (GrantedAuthority grantedAuthority : authorities) {
                // 包含其中一个角色即可访问
                if (grantedAuthority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("SimpleGrantedAuthority!!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
